import { defineStore } from "pinia";
import { ref, computed } from "vue";

export const useWebsiteStore = defineStore(
  "websiteStore",
  () => {
    const website = ref([]);

    function add(item) {
      if (website.value.find((site) => site.url === item.url) && website.value.length) {
        myApi.alert("此网站已被添加");
      } else {
        website.value.unshift(item);
      }
    }

    function del(url) {
      website.value = website.value.filter((site) => site.url !== url);
    }

    const searchValue = ref("");
    const find = computed(() => {
      if (searchValue.value === "") website.value;
      if (website.value.length) {
        let partten = new RegExp(searchValue.value, "i");
        return website.value.filter((item) => partten.test(item.title) || partten.test(item.url));
      }
    });
    return { website, add, del, searchValue, find };
  },
  {
    persist: {
      enabled: true,
      strategies: [
        {
          key: "website",
          storage: localStorage,
          paths: ["website"],
        },
      ],
    },
  }
);
